<template>
    <view id="index">
        <view>
            <u--form class="form" :model="form" ref="uForm" labelWidth="80">

                <u-form-item :required="true" label="延假类型" prop="leaveType" @click="LeaveTypeShow = true;" ref="item1">
                        <u--input v-model="form.leave_type_name" disabled disabledColor="#ffffff" placeholder="请选择请假类型"
                            ></u--input>
                        <!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
                </u-form-item>

                <u-form-item :required="true" label="延假原因" prop="cause">
                    <uni-easyinput type="textarea" v-model="form.cause" trim="all" placeholder="请输入延假原因"></uni-easyinput>
                </u-form-item>
                
                <u-form-item :required="true" label="开始时间" prop="beginTime" ref="item1">
                    <u--input v-model="form.beginTime" disabled disabledColor="#e6e6e6" placeholder="请选择开始时间"
                       ></u--input>
                    <!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
                </u-form-item>

                <u-form-item :required="true" label="截至时间" prop="endTime" @click="EndTimeShowIsShow" ref="item1">
                    <u--input v-model="form.endTime" disabled disabledColor="#ffffff" placeholder="请选择截至时间"
                        ></u--input>
                    <!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
                </u-form-item>

                <u-form-item label="上传图片" prop="files">
                    <!--文件上传-->
                    <u-upload
                        accept="image"
                        capture="camera"
                        :fileList="fileList"
                        name="1"
                        multiple
                        @afterRead="afterRead"
                        uploadIcon="plus"
                        :maxCount="3"
                        width="60"
                        height="60"
                        @delete="deleteFile"
                    ></u-upload>
                </u-form-item>

                <u-form-item label="延假天数" prop="duration">
                    <!-- <u-input class="day" v-model="form.duration" border="none" :disabled="true" /> -->
                    <view>{{form.duration}} 天</view>
                </u-form-item>

                <u-button class="button" text="提交" type="primary" @click="submitAppltLeave()"></u-button>
            </u--form>

            <!-- 请假类型 -->
            <u-action-sheet :closeOnClickOverlay="false" :show="LeaveTypeShow" :actions="LeaveTypesOptions" title="请选择请假类型" @close="LeaveTypeShow = false" @select="LeaveTypeSelect"></u-action-sheet>

            <!-- 开始时间选择器 -->
            <!-- <u-datetime-picker
                ref="datetimePicker"
                :show="BeginTimeShow"
                v-model="time"
                mode="shiro-datetime-no-minute"
                :minDate="minBeginDate"
                :maxDate="maxBeginDate"
                :closeOnClickOverlay="true"
                :formatter="formatterTime"
                @confirm="BeginTimeConfirm"
                @cancel="BeginTimeCancel"
            ></u-datetime-picker> -->
            
            <!--截至时间选择器 -->
            <u-datetime-picker
                ref="datetimePicker"
                :show="EndTimeShow"
                v-model="time"
                mode="shiro-datetime-no-minute"
                :minDate="minEndDate"
                :maxDate="maxEndDate"
                :closeOnClickOverlay="true"
                :formatter="formatterTime"
                @confirm="EndTimeConfirm"
                @cancel="EndTimeCancel"
            ></u-datetime-picker>
        </view>

    </view>
</template>
<script>
import { getExtendLeave, applyLeave, checkExtendLeaveTime, checkStuLeaveTime } from "@/api/client/leave";
import { getDicts } from "@/api/system/dict/data";
import { getUser } from "@/utils/auth";
import upload from "@/utils/upload";
export default {
    onLoad(){
        getExtendLeave().then(res => {
            this.lastLeave = res.data;
            this.form.beginTime = this.lastLeave.endTime;
            this.form.beginTimestamp = new Date(this.lastLeave.endTime).getTime();
        });
        getDicts("leave_types").then((response) => {
            //遍历字典数组并重新赋值LeaveTypesOptions
            this.LeaveTypesOptions = response.data.map(item => {
                return {
                    name: item.dictLabel,
                    value: item.dictValue
                };
            });
        });
        this.user = getUser();
    },
    data() {
        return {
            lastLeave: {},
            fileList:[],
            // 请假类型选择器
            LeaveTypeShow: false,
            // 开始时间选择器
            BeginTimeShow: false,
            // 结束时间选择器
            EndTimeShow: false,
            LeaveTypesOptions:  [],
            user: null,
            form: {
                stu: "",
                cause: "",
                gradeId: "",
                leave_type_name: "",
                leaveType: null,
                beginTimestamp: null,
                beginTime: null,
                endTimeStamp: null,
                endTime: null,
                duration: 0,
                fileIds:null,
            },
            // 时间选择器
            time: "",

            // 设置当前年份月份日期以及当前小时为开始时间
            minBeginDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), new Date().getHours()).getTime(),
            // 设置后几个月的时间为结束时间
            maxBeginDate: new Date(new Date().getFullYear(), new Date().getMonth() + 3, new Date().getDate()).getTime(),

            // 设置结束时间限制
            minEndDate: null,
            maxEndDate: null,
            rules: {
                cause: {
                    type: "string",
                    required: true,
                    message: "请填写延假原因",
                    trigger: ["blur", "change"],
                },
                leaveType: {
                    required: true,
                    message: "请选择延假类型",
                    trigger: ["blur", "change"],
                },
                beginTime: {
                    required: true,
                    message: "请选择开始时间",
                    trigger: ["blur", "change"],
                },
                endTime: {
                    required: true,
                    message: "请选择截至时间",
                    trigger: ["blur", "change"],
                },
            },
        }
    },
    methods:{
        // 添加至文件列表
        async afterRead(event) {
            if (!event.file.type == 'image') {
                this.$modal.msgError('只能上传图片文件!');
                return;
            }
            if (event.file.size > 20 * 1024 * 1024) {
                this.$modal.msgError('图片大小不能超过20M!');
                return;
            }
			let lists = [].concat(event.file)
			lists.map((item) => {
				this.fileList.push({
					...item,
				})
			})
		},
        // 删除文件
        deleteFile(event){
            this.fileList.splice(event.index,1)
        },
        LeaveTypeSelect(e) {
            this.form.leave_type_name = e.name;
            this.form.leaveType = e.value;
            this.LeaveTypeShow = false;
        },
        formatterText(value) {
			// 让输入框只能输入数值，过滤其他字符
            return value.replace(/[^0-9]/ig, "")
        },
        formatterTime(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            if (type === 'day') {
                return `${value}日`
            }
            if (type === 'hour') {
                return `${value}时`
            }
            return value
        },
        BeginTimeCancel() {
            this.BeginTimeShow = false;
        },
        EndTimeCancel() {
            this.EndTimeShow = false;
        },
        BeginTimeConfirm(e) {
            // 将时间戳转换为时间格式
            const choiceTime = this.$moment(e.value).format("YYYY-MM-DD HH:mm:ss");
            checkStuLeaveTime({thinkTime:choiceTime}).then((response) => {
                if (!response.data) {
                    this.form.beginTimestamp = e.value;
                    this.form.beginTime = choiceTime;
                    this.time = '';
                    this.form.endTime = null;
                    this.form.endTimeStamp = null;
                    this.form.duration = '';
                    this.BeginTimeShow = false;
                } else {
                    this.$modal.msgError("开始时间与其他请假时间重叠！请检查时间!");
                }
            });
        },
        EndTimeShowIsShow() {
            if (this.form.beginTime == null) {
                this.$modal.msgError("请先选择开始时间");
                return;
            }else{
                // 根据时间戳判断最小时间，最小时间为开始时间3个小时后
                this.minEndDate = this.form.beginTimestamp + 2 * 60 * 60 * 1000;
                // 根据时间戳判断最大时间，最大时间为开始时间后4个月
                this.maxEndDate = this.form.beginTimestamp + 4 * 30 * 24 * 60 * 60 * 1000;
                this.EndTimeShow = true;
            }
        },
        EndTimeConfirm(e) {
            // 将时间戳转换为时间格式
            const choiceTime = this.$moment(e.value).format("YYYY-MM-DD HH:mm:ss");
            // 校验结束时间是否冲突
            checkStuLeaveTime({thinkTime:choiceTime}).then((response) => {
                if (!response.data) {
                    this.form.endTimeStamp = e.value;
                    // 校验请假时间段是否包含其他时间段
                    checkStuLeaveTime({beginTime:this.form.beginTime,endTime:choiceTime}).then((res) => {
                        if (!res.data) {
                            this.form.endTime = choiceTime;
                            // 计算请假时长，按天计算，不大于12小时按半天计算
                            let time = this.form.endTimeStamp - this.form.beginTimestamp;
                            let day = Math.floor(time / (24 * 60 * 60 * 1000));
                            let hour = Math.floor((time % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
                            if (hour == 0) {
                                this.form.duration = day;
                            } else if (hour <= 12) {
                                this.form.duration = day+ 0.5;
                            } else {
                                this.form.duration = day + 1;
                            }
                            this.time = '';
                            this.EndTimeShow = false;
                        } else {
                            this.$modal.msgError("当前时间段内包含了其他请假时间！请重新选择时间！");
                        }
                    })
                } else {
                    this.$modal.msgError("截至时间与其他请假时间重叠！请检查时间");
                }
            });
            // // 校验结束时间是否冲突
            // this.form.endTimeStamp = e.value;
            // // 校验请假时间段是否包含其他时间段
            // checkStuLeaveTime({thinkTime:choiceTime}).then((res) => {
            //     if (!res.data) {
            //         this.form.endTime = choiceTime;
            //         // 计算请假时长，按天计算，不大于12小时按半天计算
            //         let time = this.form.endTimeStamp - this.form.beginTimestamp;
            //         let day = Math.floor(time / (24 * 60 * 60 * 1000));
            //         let hour = Math.floor((time % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
            //         if (hour == 0) {
            //             this.form.duration = day;
            //         } else if (hour <= 12) {
            //             this.form.duration = day+ 0.5;
            //         } else {
            //             this.form.duration = day + 1;
            //         }
            //         this.time = '';
            //         this.EndTimeShow = false;
            //     } else {
            //         this.$modal.msgError("当前时间段内包含了其他请假时间！请重新选择时间！");
            //     }
            // });
        },
        submitAppltLeave() {
			this.$refs.uForm.validate().then(async res => {
                const filesId = [];
                for(const item of this.fileList){
                    const {id} = await upload({
                        url:'/common/upload',
                        filePath:item.url
                    })
                    filesId.push(id)
                }
                if (filesId.length > 0) {
                    this.form.fileIds = filesId.join(',')
                }
                this.form.parentLevelId = this.lastLeave.id;
                this.form.gradeId = this.user.gradeId;
                this.form.duration = this.form.duration * 10;
                applyLeave(this.form).then(response => {
                    this.form.duration = this.form.duration / 10;
                    this.$u.toast('提交成功');
                    this.emptyForm();
                    setTimeout(() => {
                        uni.switchTab({
                            url: '/pages/index'
                        });
                    }, 1000);
                })
			}).catch(errors => {
				uni.$u.toast('请填写完整信息')
			});
        },
        // 清空表单
        emptyForm(){
            this.form = {
                stu: "",
                gradeId: "",
                leaveType: "",
                leave_type_name: "",
                beginTime: null,
                beginTimestamp: null,
                endTime: null,
                endTimeStamp: null,
                duration: 0,
                reason: "",
                fileIds: null,
            };
            this.fileList = [];
        }
    },
    onReady() {
        //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
        this.$refs.uForm.setRules(this.rules);
        // 微信小程序需要用此写法
		this.$refs.datetimePicker.setFormatter(this.formatter);
    },
    onShow() {
        this.emptyForm();
    },
};
</script>
<style lang="scss" scoped>
#index {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 750rpx;
    height: 90vh;
    background-color: #ffffff;
    padding: 50rpx 0;
    font-size: 20rpx;

    .form{
        width: 600rpx;
        height: 70vh;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .button{
            margin-top: 30rpx;
        }
    }
}
</style>
